﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;
using System.Threading;

namespace EnglishStudy.View
{
    public partial class TranslateControl : UserControl
    {
        public TranslateControl(string translateString, string fromLanguage, string toLanguage)
        {
            InitializeComponent();
            translating(translateString, fromLanguage, toLanguage);
        }
        public TranslateControl()
        {
            InitializeComponent();

        }
        public void translating(string translateString, string fromLanguage, string toLanguage)
        {
            translateString = HttpUtility.UrlEncode(translateString);
            string url = "http://translate.google.com/translate_a/t?client=t&text=" + translateString + "&hl=en&sl=" + fromLanguage + "&tl=" + toLanguage + "&ie=UTF-8&oe=UTF-8&multires=1&otf=1&pc=1&trs=1&ssel=3&tsel=6&sc=1";
            WebClient webclient = new WebClient();
            webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webclient_DownloadStringCompleted);
            webclient.DownloadStringAsync(new Uri(url, UriKind.RelativeOrAbsolute));
        }
        void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                try
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        LayoutRoot.Visibility = Visibility.Visible;
                    });
                    //      Match CompareText = Regex.Match(e.Result, "(?<=<span id=result_box class=\"short_text\">)(.*?)(?=</span>)");
                    //       string[] TranslatedText = Regex.Split(CompareText.Value, "\">");

                    string value = "\"en\"";
                    //
                    // Split the string on line breaks.
                    // ... The return value from Split is a string array.
                    //
                    string[] TranslatedText = Regex.Split(e.Result, "\"en\"");
                    //     string[] TranslatedTExt = e.Result.Split("en", StringSplitOptions.RemoveEmptyEntries);
                    // MessageBox.Show(TranslatedText.GetValue(1).ToString());
                    TranslatedText = Regex.Split(TranslatedText[0], "\",\"");
                    string meaning = "";
                    if (TranslatedText.Count() > 2)
                    {
                        meaning = TranslatedText[0].Substring(4, TranslatedText[0].Count() - 4);
                    }
                    if (TranslatedText.Count() > 6)
                    {
                        if (TranslatedText[3].Contains("\"],[\""))
                            meaning = meaning + TranslatedText[3].Substring(5, TranslatedText[3].Count() - 5);
                    }
                    if (TranslatedText.Count() > 9)
                    {
                        if (TranslatedText[6].Contains("\"],[\""))
                            meaning = meaning + TranslatedText[6].Substring(5, TranslatedText[6].Count() - 5);
                    }

                    TextBoxTranslateTo.Text = meaning;
                    Timer myTimer = new Timer(OnTimerDone);
                    myTimer.Change(3000, Timeout.Infinite);
                }
                catch (Exception ex)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        LayoutRoot.Visibility = Visibility.Collapsed;
                    });
                }
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    LayoutRoot.Visibility = Visibility.Collapsed;
                });
            }
        }


        private void OnTimerDone(object state)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
               {
                   LayoutRoot.Visibility = Visibility.Collapsed;
               });
        }

        private string ToExtendedASCII(string html)
        {
            const string ExtendedAsciiFormat = "&#{0};";
            string encodedHtml = "";
            char[] chars = html.ToCharArray();

            foreach (char c in chars)
            {
                int ascii = Convert.ToInt32(c);
                if (ascii > 127)
                {
                    encodedHtml += string.Format(ExtendedAsciiFormat, ascii);
                }
                else
                {
                    encodedHtml += c;
                }
            }

            return encodedHtml;
        }
    }
}
